import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/pages/mine/user_realname_delete_model.dart';
import 'package:mall/core/providers/pages/mine/user_realname_model.dart';
import 'package:mall/core/providers/pages/mine/req_code_model.dart';
import 'package:mall/core/providers/pages/mine/user_realname_query_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/components/count_down_text.dart';
import 'package:mall/components/login_button.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

/// 实名认证
class AuthPage extends StatelessWidget {
  static const routeName = '/AuthPage';
  final Me args;

  AuthPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider.value(value: args),
        ChangeNotifierProvider(
          create: (context) => UserRealnameQueryModel(context.read<Auth>()),
        ),
      ],
      child: Scaffold(
        appBar: AppBar(
          title: Text('实名认证'),
        ),
        body: Consumer<UserRealnameQueryModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ViewState.error:
                return Center(
                  child: Text(model.errorMessage),
                );
              case ViewState.success:
                return _SuccessWidget();
              default:
                return Container();
            }
          },
        ),
      ),
    );
  }
}

/// 显示不同的审核状态
class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserRealnameQueryModel model = context.watch<UserRealnameQueryModel>();
    if (model.data.auditStatus == 'NOT_APPLY') {
      return _NotApplyWidget();
    }
    return _OtherStatusWidget();
  }
}

/// 未申请
class _NotApplyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => UserRealnameModel(context.read<Auth>()),
      child: SingleChildScrollView(
        child: Column(
          children: [
            _HeaderWidget(),
            Divider(
              height: 1,
            ),
            _EditWidget(),
            _BottomButtonWidget(),
          ],
        ),
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        left: 14,
        right: 8.5,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 45,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '实名认证',
            style: TextStyle(
              fontSize: 17,
            ),
          ),
          Text(
            '提示：请认真核实，以防财产损失',
            style: TextStyle(
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}

class _EditWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.vertical(
        bottom: Radius.circular(8),
      ),
      child: Consumer<UserRealnameModel>(
        builder: (context, model, child) {
          Me me = context.watch<Me>();
          // 格式化已经绑定的手机
          var mobileFormat =
              me.mobile == null || me.mobile.length < 7 ? "" : me.mobile.replaceRange(3, 7, '****');
          return Column(
            children: <Widget>[
              _EditItemWidget(
                hint: '身份证号',
                function: (value) => model.cardNo = value,
              ),
              Divider(
                height: 1,
                indent: 12,
              ),
              _EditItemWidget(
                hint: '真实姓名',
                function: (value) => model.name = value,
              ),
              Divider(
                height: 1,
                indent: 12,
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: _EditItemWidget(
                      hint: '请输入$mobileFormat验证码',
                      function: (value) => model.checkCode = value,
                    ),
                  ),
                  _GetVerifyCodeWidget(),
                ],
              ),
              Divider(
                height: 1,
                indent: 12,
              ),
              Container(
                margin: EdgeInsets.only(top: 8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    _IDCardItemWidget(
                      imageProvider: model.frontFile == null
                          ? AssetImage('assets/images/auth/img_front.png')
                          : FileImage(model.frontFile),
                      title: '拍摄正面',
                      function: (file) => model.frontFile = file,
                    ),
                    _IDCardItemWidget(
                      imageProvider: model.backFile == null
                          ? AssetImage('assets/images/auth/img_back.png')
                          : FileImage(model.backFile),
                      title: '拍摄反面',
                      function: (file) => model.backFile = file,
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.all(14),
                alignment: Alignment.centerLeft,
                child: Text(
                  '上传身份证反正面照片',
                  style: TextStyle(
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class _GetVerifyCodeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => ReqCodeModel(context.read<Auth>()),
      child: Consumer<ReqCodeModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return FlatButton(
                onPressed: null,
                child: SizedBox(
                  width: 12,
                  height: 12,
                  child: CircularProgressIndicator(),
                ),
              );
            case ViewState.success:
              return FlatButton(
                onPressed: null,
                child: CountDownText(
                  function: () => model.viewState = ViewState.idle,
                  style: TextStyle(),
                ),
              );
            default:
              return FlatButton(
                onPressed: () => _onGetVerifyCodeClicked(context),
                child: Text('获取验证码'),
              );
          }
        },
      ),
    );
  }

  void _onGetVerifyCodeClicked(BuildContext context) async {
    Me me = Provider.of(context, listen: false);
    ReqCodeModel model = Provider.of(context, listen: false);
    var result = await model.reqCode(ReqCodeModel.REAL_NAME_AUTH, me.mobile);
    switch (result) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        EasyLoading.showToast('短信发送成功');
        break;
    }
  }
}

class _EditItemWidget extends StatelessWidget {
  final String hint;
  final Function(String) function;

  _EditItemWidget({
    Key key,
    @required this.hint,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      decoration: InputDecoration(
        hintText: hint,
        border: InputBorder.none,
        contentPadding: EdgeInsets.symmetric(
          vertical: 17,
          horizontal: 12,
        ),
      ),
      onChanged: function,
    );
  }
}

class _IDCardItemWidget extends StatelessWidget {
  final ImageProvider imageProvider;
  final String title;
  final Function(File) function;

  final ImagePicker _picker = ImagePicker();

  _IDCardItemWidget({
    Key key,
    @required this.imageProvider,
    @required this.title,
    @required this.function,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: imageProvider,
                fit: BoxFit.fill,
              ),
            ),
            width: 164,
            height: 140,
          ),
          Container(
            padding: EdgeInsets.all(8),
            child: Text(
              title,
              style: TextStyle(
                color: Colors.white,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      onTap: () => _onClicked(context),
    );
  }

  void _onClicked(BuildContext context) async {
    try {
      final result = await _picker.getImage(
        source: ImageSource.camera,
        maxWidth: 200,
        maxHeight: 200,
      );
      function(File(result.path));
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }
}

class _BottomButtonWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Consumer<UserRealnameModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return LoginButton.busy();
            default:
              return LoginButton(
                title: '认证',
                function: () => _onAuthClicked(context),
              );
          }
        },
      ),
    );
  }

  void _onAuthClicked(BuildContext context) async {
    UserRealnameModel model = Provider.of(context, listen: false);
    var result = await model.userRealname();
    switch (result) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        EasyLoading.showToast('认证信息已提交');
        final UserRealnameQueryModel userRealnameQueryModel = Provider.of(context, listen: false);
        userRealnameQueryModel.refreshData();
        break;
    }
  }
}

/// 其他状态
class _OtherStatusWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserRealnameQueryModel model = Provider.of(context, listen: false);
    return SingleChildScrollView(
      child: Column(
        children: [
          _HeaderWidget(),
          Column(
            children: <Widget>[
              ListTile(
                title: Text('身份证：${model.data.cardNo}'),
              ),
              Divider(
                height: 1,
                indent: 12,
              ),
              ListTile(
                title: Text('姓名：${model.data.name}'),
              ),
              Divider(
                height: 1,
                indent: 12,
              ),
              Container(
                margin: EdgeInsets.only(
                  top: 8,
                  bottom: 8,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    CachedNetworkImage(
                      imageUrl: model.data.front ?? '',
                      width: 164,
                      height: 140,
                      fit: BoxFit.fill,
                    ),
                    CachedNetworkImage(
                      imageUrl: model.data.back ?? '',
                      width: 164,
                      height: 140,
                      fit: BoxFit.fill,
                    )
                  ],
                ),
              ),
              if (model.data.auditStatus == 'AUDIT_FAIL') ...[
                Divider(height: 1, indent: 12),
                ListTile(
                  title: Text('审核失败：${model.data.auditNote}'),
                ),
              ]
            ],
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 90),
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Container(
                  width: 256,
                  height: 64,
                  child: RaisedButton(
                    onPressed: null,
                    child: Text(
                      model.data.auditStatusStr ?? '',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                ),
                if (model.data.auditStatus != 'AUDIT_SUCCESS') ...[
                  SizedBox(
                    height: 10,
                  ),
                  ChangeNotifierProvider(
                    create: (context) => UserRealnameDeleteModel(context.read<Auth>()),
                    child: Consumer<UserRealnameDeleteModel>(
                      builder: (context, model, child) {
                        switch (model.viewState) {
                          case ViewState.busy:
                            return Container(
                              width: 256,
                              height: 64,
                              child: RaisedButton(
                                onPressed: null,
                                child: CircularProgressIndicator(),
                              ),
                            );
                          default:
                            return Container(
                              width: 256,
                              height: 64,
                              child: RaisedButton(
                                onPressed: () {
                                  _onDeleteClicked(context);
                                },
                                child: Text(
                                  "删除",
                                  style: TextStyle(fontSize: 18),
                                ),
                              ),
                            );
                        }
                      },
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _onDeleteClicked(BuildContext context) async {
    UserRealnameQueryModel userRealnameQueryModel = context.read<UserRealnameQueryModel>();
    UserRealnameDeleteModel userRealnameDeleteModel = context.read<UserRealnameDeleteModel>();
    final viewState =
        await userRealnameDeleteModel.userRealnameDelete(userRealnameQueryModel.data.id);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(userRealnameDeleteModel.errorMessage);
        break;
      default:
        userRealnameQueryModel.refreshData();
        break;
    }
  }
}
